package com.lazycat.backend.service.impl.chat;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.lazycat.backend.mapper.GroupMessageMapper;
import com.lazycat.backend.pojo.GroupMessages;
import com.lazycat.backend.service.chat.GetGroupMessagesService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

@Service
public class GetGroupMessageServiceImpl implements GetGroupMessagesService {

    @Autowired
    private GroupMessageMapper groupMessageMapper;

    @Override
    public HashMap<String, Object> get(Integer groupId) {
        HashMap<String, Object> resp = new HashMap<>();
        QueryWrapper<GroupMessages> groupMessagesQueryWrapper = new QueryWrapper<>();
        groupMessagesQueryWrapper.eq("group_id", groupId).orderByDesc("time");
        List<GroupMessages> groupMessages = groupMessageMapper.selectList(groupMessagesQueryWrapper);
        ArrayList<JSONObject> items = new ArrayList<>();
        for (GroupMessages groupMessage : groupMessages) {
            JSONObject item = new JSONObject();
            item.put("group_id", groupMessage.getGroupId());
            item.put("sender_id", groupMessage.getSenderId());
            item.put("message", groupMessage.getMessage());
            item.put("time", groupMessage.getTime());
            items.add(item);
        }
        resp.put("error_message", "success");
        resp.put("messages", items);
        return resp;
    }
}
